<?php
    require_once '../funciones.php';
    $con = con_caweb();
	
	$page = $_REQUEST['page']; 

	// get how many rows we want to have into the grid - rowNum parameter in the grid 
	$limit = $_REQUEST['rows']; 

	// get index row - i.e. user click to sort. At first time sortname parameter -
	// after that the index from colModel 
	$sidx = $_REQUEST['sidx']; 
	
	// sorting order - at first time sortorder 
	$sord = $_REQUEST['sord']; 

	// if we not pass at first time index use the first column for the index or what you want
	if(!$sidx) $sidx =1; 
        $where = "";
        $fechaIni   = ($_REQUEST['fecIni'] != "")?$_REQUEST['fecIni']:'1986-01-01';
        $fechaFin   = ($_REQUEST['fecFin'] != "")?$_REQUEST['fecFin']:'2999-01-01';
        $nit        = $_REQUEST['nit'];
        $where .= ($nit != "")?" and nota.cliente = '$nit' ":"";
        $where .= " and nota.notaFecha between '$fechaIni' and '$fechaFin' ";
        if($_REQUEST['_search'] == 'true'){
            $qopers = array(  'eq'=>" = ",
                              'ne'=>" <> ",
                              'lt'=>" < ",
                              'le'=>" <= ",
                              'gt'=>" > ",
                              'ge'=>" >= ",
                              'bw'=>" LIKE ",
                              'bn'=>" NOT LIKE ",
                              'in'=>" IN ",
                              'ni'=>" NOT IN ",
                              'ew'=>" LIKE ",
                              'en'=>" NOT LIKE ",
                              'cn'=>" LIKE " ,
                              'nc'=>" NOT LIKE " );
          switch ($_REQUEST['searchOper']) {
              case 'cn': $_REQUEST['searchString'] = "%{$_REQUEST['searchString']}%"; break;
              case 'bw': $_REQUEST['searchString'] = "{$_REQUEST['searchString']}%"; break;
              case 'ew': $_REQUEST['searchString'] = "%{$_REQUEST['searchString']}"; break;
              default:
                  break;
          }
        $where = "and ".$_REQUEST['searchField']." ".$qopers[$_REQUEST['searchOper']]." '{$_REQUEST['searchString']}'";
        }
	// calculate the number of rows for the query. We need this for paging the result 
	$result = mysql_query("SELECT COUNT(*) AS count FROM cabeceras_nota WHERE 1 = 1 $where ");
	$row = mysql_fetch_array($result,MYSQL_ASSOC); 
	$count = $row['count']; 

	// calculate the total pages for the query 
	if( $count > 0 ) $total_pages = ceil($count/$limit); 
	else $total_pages = 0; 

	// if for some reasons the requested page is greater than the total 
	// set the requested page to total page 
	if ($page > $total_pages) $page=$total_pages;

	// calculate the starting position of the rows 
	$start = $limit*$page - $limit;

	// if for some reasons start position is negative set it to 0 
	// typical case is that the user type 0 for the requested page 
	if($start <0) $start = 0; 

	// the actual query for the grid data
	 
	$SQL = "SELECT cli.name,nota.* FROM cabeceras_nota nota
                inner join clientes cli on cli.nit = nota.cliente WHERE 1 = 1 $where ORDER BY $sidx $sord LIMIT $start , $limit";
	$result = mysql_query( $SQL ) or die("Error en clientes.".mysql_error().$SQL);

	// we should set the appropriate header information
	if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
				  header("Content-type: application/xhtml+xml;charset=utf-8"); 
	} else {
			  header("Content-type: text/xml;charset=utf-8");
	}
	echo "<?xml version='1.0' encoding='utf-8'?>";
	echo "<rows>";
	echo "<page>".$page."</page>";
	echo "<total>".$total_pages."</total>";
	echo "<records>".$count."</records>";
//        echo "<sql>".$SQL."</sql>";
        $sql = "SELECT sum(nota.notaTotal) as totales FROM cabeceras_nota nota
                inner join clientes cli on cli.nit = nota.cliente WHERE 1 = 1 $where";
        $totales = mysql_query($sql,$con) or die("Error SQL 54".mysql_error().$sql);
        echo "<row id='a'>";
        echo "<cell></cell><cell></cell><cell></cell><cell>Total</cell>";
        echo "<cell>".  number_format(mysql_result($totales, 0,"totales"),0,'.',',')."</cell>";
        echo "<cell></cell><cell></cell><cell></cell><cell></cell>";
        echo "</row>";
	while($row = mysql_fetch_array($result)) {
            echo "<row id='". $row['notaNumero']."'>";
            if($row['estado'] == 'V' || $row['estado'] == 'Aplicada') echo "<cell>Imprimir</cell>";
            else echo "<cell>No Autorizado</cell>";
            $sql = "select nombre from ciudades where codigociudad = '{$row['sucursal']}'";
            $r = mysql_query($sql, $con) or die("Erorr SQL ".mysql_error().$sql);
            echo "<cell>". mysql_result($r, 0,"nombre")."</cell>";
            echo "<cell>". $row['notaNumero']."</cell>";
            echo "<cell>". utf8_encode(htmlspecialchars($row['name']))."</cell>";
            echo "<cell>". number_format($row['notaTotal'],0,',','.')."</cell>";
            echo "<cell>". $row['notaFecha']."</cell>";
            echo "<cell>". utf8_encode(htmlspecialchars($row['notaPiepagina']))."</cell>";
            echo "<cell>". utf8_encode(htmlspecialchars($row['notaConcepto']))."</cell>";
            $sql = "select recaudo from recaudos where notaNumero = '{$row['notaNumero']}'";
            $r = mysql_query($sql,$con) or die("Error SQL 34".mysql_error().$sql);
            if(mysql_num_rows($result) > 0)
                echo "<cell>". mysql_result($r, 0,"recaudo")."</cell>";
            else echo "<cell>No Aplicado</cell>";
            echo "</row>";
	}
	echo "</rows>"; 
?>
